package com.example.sls.service.impl.account;

import com.example.sls.mapper.account.AccountMapper;
import com.example.sls.pojo.account.Account;
import com.example.sls.service.account.LoginService;
import com.example.sls.service.impl.userDetails.UserDetailsImpl;
import com.example.sls.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public Map<String, String> getToken(String username, String password, String roleId) {

//        System.out.println("========");
//        System.out.println("username : " + username);
//        System.out.println("password : " + password);
//        System.out.println("roleId : " + roleId);
//        System.out.println("========");

        Map<String, String> result = new HashMap<>();
        Account acc = accountMapper.getAccountByUserName(username);
        if( acc.getRoleId() != Integer.parseInt(roleId) ){
            result.put("error_message", "账号信息不符");
            return result;
        }
//        if(roleId == null){
//            map.put("error_message","必须选择你的角色");
//            return map;
//        }

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(username, password);

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);  // 登录失败，会自动处理
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();
        Account user = loginUser.getUser();

//        Integer rid = Integer.parseInt(roleId);
//        if(rid != user.getId()){
//            map.put("error_message","您选择的角色不符");
//            return map;
//        }


        String jwt = JwtUtil.createJWT(user.getId().toString());

        result.put("error_message", "success");
        result.put("token", jwt);
        result.put("roleId", roleId);

        return result;
    }
}

